import { defineStore } from "pinia";
import store from "../index";
import { getAllLookupApi } from "@/api/configCenter/dataDictManagement";
import { getAllClientCodeApi, getProvinceApi } from "@/api/common";
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
interface PermissionStore {
  dataDict: Base.GeneraDataType<Array<Base.GeneraDataType>>;
  clientCodeOpts: Array<Base.GeneraDataType>;
  provincesOpts: Array<Base.GeneraDataType>;
}
export const useBaseStore = defineStore("base", {
  // other options...
  state: (): PermissionStore => {
    return {
      dataDict: {}, // 常量数据字段
      clientCodeOpts: [],
      provincesOpts: []
    };
  },
  actions: {
    initAllStaticData() {
      this.initDataDict();
      this.initClientOpts();
      this.initProvince();
    },
    initDataDict() {
      return getAllLookupApi().then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          for (let i = 0; i < data.length; i++) {
            const target = data[i];
            if (!this.dataDict[target.code]) this.dataDict[target.code] = target.items;
          }
        } else {
          console.warn("获取数据字段失败!");
        }
      });
    },
    initClientOpts() {
      return getAllClientCodeApi().then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          this.clientCodeOpts = data || [];
        }
      });
    },
    initProvince() {
      return getProvinceApi().then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          this.provincesOpts = data || [];
        }
      });
    }
  },
  persist: true
});

export default useBaseStore(store);
